import chalk from "chalk";
import fs from "fs";
import path from "path";
import url from "url";

// 一些常量
const __filename = url.fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const root = path.dirname(__dirname);
const appDir = path.join(root, "src/apps");
const templatePath=path.join(root,"scripts/template/app")
const log = (msg) => console.log(chalk.green(msg));
const logSuccess = (msg) => console.log(chalk.blue(msg));
const logError = (msg) => console.log(chalk.red(msg));


// 监听用户输入
log(`请输入要创建的应用名，将作为文件夹名称`);
process.stdin.on("data", (data) => {
  console.log(`输入的内容为：${data}`);
  // 查找appDir下是否有同名文件夹
  const appName = data.toString().trim();
  const appPath = path.join(appDir, appName);
  if (fs.existsSync(appPath)) {
    logError(`应用 ${appName} 已存在，或者文件夹名称不正确，请重新输入`);
    return
  } else {
    if(!fs.existsSync(templatePath)){
      return logError(`未能找到对应模板文件`);
    }
    fs.mkdirSync(appPath);
    logSuccess(`应用 ${appName} 创建成功`);
    log('正在创建模板文件...')
    copyAllFiles(templatePath,path.join(appPath))
    logSuccess(`应用 ${appName} 创建成功`);
    process.exit();
  }
});

function copyAllFiles(sourceDir,targetDir){
  const sourceFiles=fs.readdirSync(sourceDir,{withFileTypes:true})
  sourceFiles.forEach(file=>{
    if(file.isFile()){
      // 复制文件
      const sourceFile=path.join(sourceDir,file.name)
      const targetFile=path.join(targetDir,file.name)
      fs.copyFileSync(sourceFile,targetFile)
      console.log(`复制文件 ${sourceFile} 到 ${targetFile} 成功`)
    }else {
      // 创建文件夹
      const newDir=path.join(targetDir,file.name)
      fs.mkdirSync(newDir)
      console.log(`创建文件夹 ${newDir} 成功`)
      // 递归复制文件夹
      copyAllFiles(path.join(sourceDir,file.name),newDir)
    }
  })
}
